#include "public.h"

#pragma section (fcode)

void SPI_Initialize(void)
{
	SPI_Disable();
	SPI_CR1=0b00000111;
	SPI_CR1|=SPI_SPEED_128;	
	SPI_CR2=0b01000011;
	SPI_ICR=0x40;
	spi_cnt=0;
	SPI_CheckSum = 0;
	Stop_SPI_CS;
}
void ISR_SPIRev(void)
{

	uchar SPI_RxTempData=SPI_DR;
	SPI_RxPacketBuffer[spi_cnt] = SPI_RxTempData;

	if(spi_cnt<=SPI_PACKET_SIZE-2)
    {
		if(spi_cnt != 0)	
			SPI_CheckSum += SPI_RxTempData;
        else
			SPI_CheckSum +=( PacketId==0xff)? SPI_HEAD_CODE: (PacketId|SPI_HEAD_CODE);
		spi_cnt++;

		if(spi_cnt == SPI_PACKET_SIZE-1)
        {
			if(SPI_CheckSum ==0||SPI_CheckSum ==SPI_HEAD_CODE)

				SPI_TxPacketBuffer[SPI_PACKET_SIZE-1] = SPI_END_CODE;
            else
				SPI_TxPacketBuffer[SPI_PACKET_SIZE-1] =SPI_MASTER_RX_CRC_ERROR;
        }
		Delay_us();
		Delay_us();
		Delay_us();
		Delay_us();
		Delay_us();
		Delay_us();
		Delay_us();
		Delay_us();
		Delay_us();
		Delay_us();
		Delay_us();
		SPI_DR=SPI_TxPacketBuffer[spi_cnt]; 
    }
    else
    {
		Stop_SPI_CS;
		if(SPI_RxTempData != SPI_ACK_CHECK_CODE)
			SetBit(SPI_TxRxFlag, SPI_TxERROR);

		SetBit(SPI_TxRxFlag, SPI_NewPacket);

    }
}

static void SetPacket(void)
{
	uchar PacketChecksum=0,temp=0,ptr=0,i=0;

	SPI_TxPacketBuffer[0]=PacketId;
	SPI_TxPacketBuffer[0]|=SPI_HEAD_CODE;
	ptr=PacketId*8;


	PacketChecksum=PacketId|SPI_HEAD_CODE;

	for(i=1;i<9;i++)
    {
		temp=SPI_TxBuffer[ptr];

		SPI_TxPacketBuffer[i]=temp;
		PacketChecksum+=temp;
		ptr++;
	}
	SPI_TxPacketBuffer[9]=~PacketChecksum+1;
	SPI_TxPacketBuffer[10]=0;

}

static void GetPacket(void)
{
	uchar ptr=0,i=0;
	ptr=8*PacketId;
	for(i=1;i<9;i++)
    {
		SPI_RxBuffer[ptr]=SPI_RxPacketBuffer[i];
		ptr++;
    }
}

void SPI_RePacketAnalyse(void)
{
	uchar RxLength=0, TxLength=0, Packet_length=0;
	if(GetBit(SPI_TxRxFlag, SPI_TxERROR)) 
    {
		 ClrBit(SPI_TxRxFlag, SPI_TxERROR);

    }
    else
    {
		if(0 == PacketId)
        {
			RxLength = SPI_RxPacketBuffer[1];
			TxLength = Data_Length_IN_Buffer;

			if(RxLength > SPI_BUFFER_SIZE||RxLength == 0) 
				Packet_length = TxLength;
            else
				Packet_length = MAX(RxLength, TxLength);
			MaxId =(uchar) ((Packet_length  +DATA_SIZE_PER_PACKET - 1)/DATA_SIZE_PER_PACKET);
        }
		if(PacketId != 0xff)	
			GetPacket();
		PacketId++;
		if((PacketId == MaxId)&&MaxId )
        {
			SetBit(SPI_TxRxFlag,SPI_TxEnd);
			return;
        }
    }
	Start_SPI_CS;
	SPI_SCK=1;
	if(PacketId != 0xff)	
		SetPacket();
    else
		PacketId=0;;

	M_WAIT;
	M_WAIT;
	SPI_Start();
	SPI_Enable();
}



void SPI_StartFrame(void)
{
	ClrBit(SPI_TxRxFlag, SPI_TxERROR);
	SetBit(SPI_TxRxFlag, SPI_Busy);
	SetBit(SPI_TxRxFlag, SPI_NewPacket);
	PacketId = 0xff;
	MaxId = 1;
}

#pragma section ()

